package xx.pro.producer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class QueueConfiguration {
    /**
     * 创建两个队列，处理顺序消息
     */
    @Bean
    public Queue seqQueue1() {
        return creatQueue("q_seq1");
    }

    @Bean
    public Queue seqQueue2() {
        return creatQueue("q_seq2");
    }
    // 交换机
    @Bean
    public DirectExchange seqDirectExchange() {
        return new DirectExchange("direct_seq");
    }

    // 队列绑定交换机，执行路由key
    @Bean
    public Binding seqBinding1() {
        return BindingBuilder.bind(seqQueue1()).to(seqDirectExchange()).with("1");
    }

    @Bean
    public Binding seqBinding2() {
        return BindingBuilder.bind(seqQueue2()).to(seqDirectExchange()).with("2");
    }

    /**
     * 创建一个 单活模式的队列
     * @param name
     * @return queue
     */
    private Queue creatQueue(String name) {
        HashMap<String, Object> args = new HashMap<>();
        // x-single-active-consumer 单活模式 队列
        // 表示是否最多只允许一个消费者消费，如果有多个消费者同时绑定，则只会激活第一个，
        // 除非第一个消费者被取消或者死亡，才会自动转到下一个消费者。
        args.put("x-single-active-consumer", true);
        return new Queue(name, true, false, false, args);
    }
}
